<template>
  <AppTitle title="修改密码"></AppTitle>
  <div class="form-box">
  <div class="form">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="原密码" prop="oldPwd">
        <el-input v-model="ruleForm.oldPwd" placeholder="请输入原密码" @blur="verifyOldPwd"/>
      </el-form-item>
      <el-form-item label="新密码" prop="newPwd">
        <el-input v-model="ruleForm.newPwd" placeholder="请输入新密码" />
      </el-form-item>
      <el-form-item label="确定密码" prop="newPwd1">
        <el-input v-model="ruleForm.newPwd1" placeholder="请再次输入新密码" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">
          立即修改
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</div>
</template>

<script setup>
import AppTitle from '@/components/AppTitle.vue';
import { accountEditPwd,accountCheckoldpwd } from '@/api/account';
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
const router = useRouter();

const ruleFormRef = ref();

const ruleForm = reactive({
  newPwd: '',
  newPwd1:'',
  oldPwd: '',
  id: JSON.parse(sessionStorage.getItem('user')).id
});
const checkoldPwd = (rule, value, callback) => {
  const reg = /^([a-z]|[0-9]){5,11}$/;
  if (!reg.test(value)) {
    callback(new Error('密码长度为5-11位'))
  } else {
    callback()
  }
}
// 验证旧密码
const verifyOldPwd = async()=>{
  let res = await accountCheckoldpwd({id:JSON.parse(sessionStorage.getItem("user")).id,oldPwd:ruleForm.oldPwd})
  if(res.code==0){
    ElMessage.success("密码正确");
  }else{
    ElMessage.error("密码输入错误");
  }
}

// 验证密码是否一致
const validatePassword1 = (rule,value,callback) => {
     //确认密码 是否 新密码一直 如果一致成功 不一致提示用户
     if(value !== ruleForm.newPwd){
       callback(new Error('两次密码不一致'))
     }else{
       callback()
     }
}
const rules = reactive({
  oldPwd:[
    { required: true, validator: verifyOldPwd, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPwd:[
    { required: true, validator: checkoldPwd, message: '请输入新密码', trigger: 'blur' }
  ],
  newPwd1:[
    { required:true,message:'请输入确认密码',trigger:'blur'},
    { validator: validatePassword1, trigger: 'blur'  }
  ]
})

const submitForm = async () => {
  let res = await accountEditPwd(ruleForm);
  if(ruleForm.newPwd==ruleForm.newPwd1){
    if (res.code == 0) {
    ElMessage.success(res.msg);
    router.push('/login');
  }else{
    ElMessage.error(res.msg);
  }
  }
  else{
    ElMessage.error('两次密码不一致')
  }
};
</script>

<style lang="scss" scoped>
.form-box {
  width: 100%;
  height: 252px;
  overflow: hidden;
}
.form {
  width: 100%;
  height: 252px;
  padding: 15px;
}
.el-form-item:nth-last-child(1) {
  margin-left: 50px;
}
:deep(.el-form) {
  width: 400px;
  height: 230px;
  margin-left: 46px;
}
</style>